package com.example.javabasic.thread.classtwo.lock.demo1;

import java.util.Random;

public class WriteWorker extends Thread {
    //随机数
    private static final Random random = new Random(System.currentTimeMillis());
    //共享数据
    private final ShareData data;
    //
    private final String filler;
    //下标
    private int index = 0;

    //构造器
    public WriteWorker(ShareData data, String filler) {
        this.data = data;
        this.filler = filler;
    }

    @Override
    public void run() {
        //写进去
        try {
            while (true) {
                //获取字符
                char c = nextChar();
                data.write(c);
                Thread.sleep(random.nextInt(1000));
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    //下一个字符
    private char nextChar() {
        char c = filler.charAt(index);
        index++;
        //如果写完了 从头开始
        if (index >= filler.length()) {
            index = 0;
        }
        return c;
    }
}
